﻿using AutoMapper;
using MediatR;
using WeatherHistory.Data.Repositories.Interfaces;
using WeatherHistory.Shared.Exceptions;

namespace WeatherHistory.Api.CommandsQueries.Commands.RegionTypes.Update;

public class UpdateRegionTypesCommandHandler : IRequestHandler<UpdateRegionTypesCommandRequest, UpdateRegionTypesCommandResponse>
{
    private readonly IMapper _mapper;
    private readonly IRegionTypeRepository _regionTypeRepository;

    public UpdateRegionTypesCommandHandler(IMapper mapper, IRegionTypeRepository regionTypeRepository)
    {
        _mapper = mapper;
        _regionTypeRepository = regionTypeRepository;
    }

    public async Task<UpdateRegionTypesCommandResponse> Handle(UpdateRegionTypesCommandRequest request, CancellationToken cancellationToken)
    {
        var regionType = await _regionTypeRepository.FirstOrDefaultAsync(x => x.Id == request.Id, cancellationToken);
        if (regionType == null) throw new NotFoundException($"Тип региона с id '{request.Id}' не найден");

        var regionTypeExists = await _regionTypeRepository.AnyAsync(x => x.Name == request.Type && x.Id != request.Id, cancellationToken);
        if (regionTypeExists) throw new ConflictException("Тип региона с таким именем уже существует");

        regionType.Name = request.Type;

        await _regionTypeRepository.UpdateAsync(regionType, cancellationToken);
        return _mapper.Map<UpdateRegionTypesCommandResponse>(regionType);
    }
}